﻿using NModbus;
using NModbus.Serial;
using System.IO.Ports;
using System.Text;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ModbusDemo
{
    internal class Program
    {
        //static SerialPort serialPort = new SerialPort("COM19");
        static void Main(string[] args)
        {
            // 主修改从、主读取从
            // 修改为您的串口名称和波特率
            string portName = "COM19"; // 串口名称，例如 COM1
            try
            {

                // 创建串口并配置
                using (var serialPort = new SerialPort(portName))
                {
                    serialPort.BaudRate = 9600;
                    serialPort.DataBits = 8;
                    serialPort.Parity = Parity.None;
                    serialPort.StopBits = StopBits.One;
                    serialPort.Open();
                    Console.WriteLine($"成功连接到 {portName} 端口");

                    //serialPort.DataReceived += SerialPort_DataReceived;

                    // 创建Modbus工厂
                    var factory = new ModbusFactory();
                    // 创建Modbus RTU主机
                    var master = factory.CreateRtuMaster(serialPort);

                    // 读取保持寄存器（地址为0的寄存器，读取10个寄存器）
                    byte slaveId = 1; // 从站ID
                    ushort startAddress = 0; // 寄存器起始地址
                    ushort registerCount = 10; // 寄存器数量

                    int count = 0;
                    //TODO 异步接收
                    do
                    {
                        ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, registerCount);
                        // 输出读取的寄存器值
                        Console.WriteLine($"读取的保持寄存器值A {count}:");
                        for (int i = 0; i < registers.Length; i++)
                        {
                            Console.WriteLine($"Register A {startAddress + i}={registers[i]}");
                        }
                        Thread.Sleep(5000);

                        ushort[] vals = new ushort[10];
                        for (int i = 0; i < 10; i++)
                        {
                            Random rdm = new Random();
                            var v = rdm.Next(256);
                            vals[i] = (ushort)Convert.ToInt16(v);
                        }
                        master.WriteMultipleRegisters(1, 0, vals);


                        registers = master.ReadHoldingRegisters(slaveId, startAddress, registerCount);
                        // 输出读取的寄存器值
                        Console.WriteLine($"读取的保持寄存器值B {count}:");
                        for (int i = 0; i < registers.Length; i++)
                        {
                            Console.WriteLine($"Register B {startAddress + i}={registers[i]}");
                        }
                        count++;
                    }
                    while (count < 2);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            Console.WriteLine("按任意键退出程序......");
            Console.ReadKey();
        }

        //private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{
        //    byte[] buffer = new byte[serialPort.BytesToRead];
        //    int count = serialPort.Read(buffer, 0, serialPort.BytesToRead);
        //    //string data = Encoding.Default.GetString(buffer);
        //    //Console.WriteLine($"接收到的数据: {data}" + data);
        //    for (int i = 0; i < buffer.Length; i++)
        //    {
        //        Console.WriteLine($"接收到的数据: {buffer[i]}");
        //    }
        //}
    }
}
